﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows.Forms;

namespace TEL.TelPhoneF
{
    static class Program
    {
        public static System.Threading.Mutex Mutex;

        [DllImport("user32.dll")]
        static extern bool ShowWindow(IntPtr hWnd, int nCmdShow);

        [DllImport("user32.dll")]
        static extern bool SetForegroundWindow(IntPtr hWnd);

        [DllImport("user32.dll")]
        public static extern IntPtr FindWindow(String sClassName, String sAppName);



        internal const int SW_HIDE = 0;
        internal const int SW_SHOWNORMAL = 1;
        internal const int SW_NORMAL = 1;
        internal const int SW_SHOWMINIMIZED = 2;
        internal const int SW_SHOWMAXIMIZED = 3;
        /// <summary>
        /// Главная точка входа для приложения.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {

            bool ok;
            string mainFormTitle = "Simple Phone - Телефон";
            Mutex = new System.Threading.Mutex(true, "Local\\simplePhone", out ok);
            if (!ok)
            {
                try
                {
                    System.Diagnostics.Process[] process =
                        System.Diagnostics.Process.GetProcessesByName(Application.ProductName);
                    if (process.Length == 0)
                    {
                    }
                    else
                    {
                        if (args.Length > 0 && args[0] == "kill")
                        {
                          //  process[0].Kill();
                            EventWaitHandle ew = EventWaitHandle.OpenExisting(Form1.EventWaitname);
                            ew.Set();
                        }
                        else
                        {
                            IntPtr h = FindWindow(null, mainFormTitle);
                            ShowWindow(h, SW_NORMAL);
                            SetForegroundWindow(h);
                        }
                    }
                }
                catch (Exception error)
                {
                }
            }
            else
            {
                try
                {
                    if( args.Length >0 && args[0] == "kill")
                    {
                        return;
                    }
                   

                    Application.EnableVisualStyles();
                    Application.SetCompatibleTextRenderingDefault(false);
                    Form1 form1 = new Form1() { Text = mainFormTitle };
                    Application.Run(form1);
                }
                catch (Exception)
                {
                }

            }

        }
    }
}
